package org.example.tree;

/**
 * @author liyishan
 * @date 2024/2/22 11:13
 * @apiNote
 */

public class Test00110IsBalanced {
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }else{
            return Math.abs(height(root.left) -height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
        }
    }

    public static int height(TreeNode root){
        if(root == null){
            return 0;
        }else{
            return Math.max(height(root.left),height(root.right))+1;
        }
    }

    public boolean isBalanced1(TreeNode root){
        return height1(root) >= 0;
    }


    public static int height1(TreeNode root){
        if(root == null){
            return 0;
        }
        int leftHeight = height1(root.left);
        int rightHeight = height1(root.right);
        if(leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1){
            return -1;
        }else{
            return Math.max(leftHeight,rightHeight)+1;
        }
    }
}
